﻿using IDEAMS.core;
using IDEAMS.utils;
using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IDEAMS.model
{
    public class RoasterRecordCollection : SHCollection<RoasterRecord>
    {
        private static ILog logger = LogManager.GetLogger(typeof(RoasterRecordCollection));

        public RoasterRecordCollection() { }

        public RoasterRecordCollection(RoasterRecordCollection collection)
        {
            collection.ForEach(x =>
            {
                RoasterRecord data = new RoasterRecord(x);
                dataList.Add(data);
                return false;
            });
        }

        public override bool Equals(RoasterRecord obj,object key)
        {
            return (string)key == obj.serialNo;
        }

        public override void CopyTo(RoasterRecord src, RoasterRecord dst)
        {
            dst.Copy(src);
        }

        public RoasterRecordCollection Clone()
        {
            return new RoasterRecordCollection(this);
        }

        public bool Save()
        {
            bool rn = true;
            rwLock.EnterReadLock();
            try
            {
                string dataFile = TW_App.fileManager.roasterRecordCollectionFile;
                rn = XmlUtil.Save<RoasterRecordCollection>(dataFile, this);
            }
            finally
            {
                rwLock.ExitReadLock();
            }
            return rn;
        }

        public int Load()
        {
            int rn = -1;
            rwLock.EnterWriteLock();
            try
            {
                string dataFile = TW_App.fileManager.roasterRecordCollectionFile;
                bool existsFlag = File.Exists(dataFile);
                if (!existsFlag)
                {
                    logger.WarnFormat("烤机记录文件[{0}]不存在", dataFile);
                    return -2;
                }

                RoasterRecordCollection collection = XmlUtil.Load<RoasterRecordCollection>(dataFile);
                if (collection != null)
                {
                    dataList.Clear();
                    collection.ForEach(x =>
                    {
                        RoasterRecord data = x.Clone();
                        dataList.Add(data);

                        return false;
                    });
                    rn = 0;
                }
                else
                {
                    logger.ErrorFormat("加载烤机记录[{0}]失败", dataFile);
                    rn = -1;
                }
            }
            finally
            {
                rwLock.ExitWriteLock();
            }
            return rn;
        }
    }
}
